﻿'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
'
'Copyright (c) 2011, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Will Strohl, Google Plus for DotNetNuke, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.Common
Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.UI.Skins.Skin
Imports DotNetNuke.UI.Skins.Controls.ModuleMessage
Imports DotNetNuke.Services.Exceptions
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Plus.v1
Imports Google.Apis.Plus.v1.Data
Imports System.Net
Imports WillStrohl.Modules.GooglePlus.GooglePlusController
Imports DotNetOpenAuth.OAuth2

Namespace WillStrohl.Modules.GooglePlus

    Partial Public MustInherit Class ViewProfile
        Inherits WNSPortalModuleBase
        Implements IActionable

#Region " Private Members "

        Private Const MENUITEM_SETTINGS As String = "MenuItem.Settings"
        Private Const MODULEKEY_EDIT As String = "Edit"

        Private p_ClientId As String = String.Empty
        Private p_ClientSecret As String = String.Empty
        Private p_ApiKey As String = String.Empty
        Private p_ProfileUrl As String = String.Empty

#End Region

#Region " Private Properties "

        Private ReadOnly Property GooglePlusClientId As String
            Get
                If Not String.IsNullOrEmpty(Me.p_ClientId) Then
                    Return Me.p_ClientId
                End If

                Dim obj As Object = Me.Settings(SETTINGKEY_CLIENTID)
                If Not obj Is Nothing Then
                    Me.p_ClientId = obj.ToString()
                End If

                Return Me.p_ClientId
            End Get
        End Property

        Private ReadOnly Property GooglePlusClientSecret As String
            Get
                If Not String.IsNullOrEmpty(Me.p_ClientSecret) Then
                    Return Me.p_ClientSecret
                End If

                Dim obj As Object = Me.Settings(SETTINGKEY_CLIENTSECRET)
                If Not obj Is Nothing Then
                    Me.p_ClientSecret = obj.ToString()
                End If

                Return Me.p_ClientSecret
            End Get
        End Property

        Private ReadOnly Property GooglePlusApiKey As String
            Get
                If Not String.IsNullOrEmpty(Me.p_ApiKey) Then
                    Return Me.p_ApiKey
                End If

                Dim obj As Object = Me.Settings(SETTINGKEY_APIKEY)
                If Not obj Is Nothing Then
                    Me.p_ApiKey = obj.ToString()
                End If

                Return Me.p_ApiKey
            End Get
        End Property

        Private ReadOnly Property GooglePlusProfileUrl As String
            Get
                If Not String.IsNullOrEmpty(Me.p_ProfileUrl) Then
                    Return Me.p_ProfileUrl
                End If

                Dim obj As Object = Me.Settings(SETTINGKEY_PROFILEURL)
                If Not obj Is Nothing Then
                    Me.p_ProfileUrl = obj.ToString()
                End If

                Return Me.p_ProfileUrl
            End Get
        End Property

#End Region

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Not Page.IsPostBack Then
                    Me.BindData()
                End If
            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try
        End Sub

#End Region

#Region " Helper Methods "

        Private Sub BindData()

            Me.LocalizeModule()

            If Me.SettingsReady() Then
                Me.GetGooglePlusProfile()
            End If

        End Sub

        Private Sub LocalizeModule()



        End Sub

        Private Sub GetGooglePlusProfile()

            ' Register the authenticator
            Dim uriGooglePlus As New Uri("https://www.googleapis.com/plus/v1/people/me")
            Dim oServer As New AuthorizationServerDescription
            oServer.AuthorizationEndpoint = uriGooglePlus
            Dim oClient As WebServerClient = New WebServerClient(oServer, GooglePlusClientId, GooglePlusClientSecret)
            oClient.RequestUserAuthorization(New String(0) {"https://www.googleapis.com/plus/v1/people/me"}, String.Empty, uriGooglePlus)



            Dim sb As New System.Text.StringBuilder
            ' build one or more UI elements
            Me.phTest.Controls.Add(New System.Web.UI.LiteralControl(sb.ToString()))

        End Sub

        Private Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState

            ' Get the auth URL:
            Dim state As IAuthorizationState = New AuthorizationState()
            state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
            Dim authUri As Uri = arg.RequestUserAuthorization(state)

            ' Request authorization from the user (by opening a browser window):
            Process.Start(authUri.ToString())

            Console.Write("  Authorization Code: ")
            Dim authCode As String = Console.ReadLine()
            Console.WriteLine()

            ' Retrieve the access token by using the authorization code:
            Return arg.ProcessUserAuthorization(authCode, state)

        End Function

        Private Function SettingsReady() As Boolean

            Dim blnReturn As Boolean = True

            If String.IsNullOrEmpty(Me.GooglePlusClientId) Then
                Skins.Skin.AddModuleMessage(Me, Me.GetLocalizedString("ErrorMessage.ClientId"), ModuleMessageType.RedError)
                blnReturn = True
            End If

            If String.IsNullOrEmpty(Me.GooglePlusClientSecret) Then
                If Not blnReturn Then
                    Skins.Skin.AddModuleMessage(Me, Me.GetLocalizedString("ErrorMessage.ClientSecret"), ModuleMessageType.RedError)
                End If
                blnReturn = True
            End If

            If String.IsNullOrEmpty(Me.GooglePlusApiKey) Then
                If Not blnReturn Then
                    Skins.Skin.AddModuleMessage(Me, Me.GetLocalizedString("ErrorMessage.ApiKey"), ModuleMessageType.RedError)
                End If
                blnReturn = True
            End If

            If String.IsNullOrEmpty(Me.GooglePlusProfileUrl) Then
                If Not blnReturn Then
                    Skins.Skin.AddModuleMessage(Me, Me.GetLocalizedString("ErrorMessage.ProfileUrl"), ModuleMessageType.RedError)
                End If
                blnReturn = True
            End If

            Return blnReturn

        End Function

#End Region

#Region " IActionable Implementation "

        Public ReadOnly Property ModuleActions() As DotNetNuke.Entities.Modules.Actions.ModuleActionCollection Implements IActionable.ModuleActions
            Get
                Dim Actions As New Actions.ModuleActionCollection

                Actions.Add(GetNextActionID, Me.GetLocalizedString(MENUITEM_SETTINGS), _
                    String.Empty, String.Empty, String.Empty, _
                    EditUrl(String.Empty, String.Empty, MODULEKEY_EDIT), _
                    False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)

                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace